package model

import (
	"gf-xb-api/cwt/consts"
	"strings"
)

type FilterRule[T any] struct {
	Field   string   `json:"field"`
	Value   string   `json:"value"`
	Datas   []string `json:"datas"`
	Operate any      `json:"operate"`
}

// getFieldAlias 获得字段别名
// func (r *FilterRule[T]) getFieldAlias(fieldName string) string {
//	var zero [0]T
//	tt := reflect.TypeOf(zero).Elem()
//
//	field, isOk := tt.FieldByNameFunc(func(n string) bool { return strings.EqualFold(n, fieldName) })
//	if !isOk {
//		return ""
//	}
//
//	alias := field.Tag.Get(constant.DB_FIELD_NAME)
//	return alias
// }

func (r *FilterRule[T]) UnmarshallFilterRuleJson(ruleJson any) []*FilterRule[T] {
	if ruleJson == nil {
		return nil
	}

	rules, ok := ruleJson.([]interface{})
	if !ok {
		return nil
	}

	var result []*FilterRule[T]

	for _, rule := range rules {

		if ruleMap, ok := rule.(map[string]interface{}); ok {

			var filterRule = &FilterRule[T]{}

			for k, v := range ruleMap {

				switch strings.ToLower(k) {
				case consts.ATTR_FIELD:
					if fieldName, ok := v.(string); ok {
						filterRule.Field = fieldName

						// alias := r.getFieldAlias(fieldName)
						// if strings.TrimSpace(alias) != "" {
						//	filterRule.Field = strings.TrimSpace(alias)
						// }
					}
				case consts.ATTR_VALUE:
					if val, ok := v.(string); ok {
						filterRule.Value = val
					}
				case consts.ATTR_OPERATE:
					filterRule.Operate = v
				case consts.ATTR_DATAS:
					if datas, ok := v.([]interface{}); ok {
						var ruleDatas []string

						for _, data := range datas {
							if dataStr, ok := data.(string); ok {
								ruleDatas = append(ruleDatas, dataStr)
							}
						}

						filterRule.Datas = ruleDatas
					}
				}
			}

			result = append(result, filterRule)
		}
	}

	return result
}
